package com.swanclouds.redfish.updates;

import com.google.common.base.Preconditions;
import com.swanclouds.api.Apis;
import com.swanclouds.api.exceptions.ResourceNotFoundException;
import com.swanclouds.api.updates.FirmwareInventoryService;
import com.swanclouds.api.updates.UpdateService;
import com.swanclouds.core.transport.ClientConstants;
import com.swanclouds.model.common.ActionResponse;
import com.swanclouds.model.updates.Update;
import com.swanclouds.model.updates.UpdateFirmware;
import com.swanclouds.redfish.common.redfish.SimpleUpdate;
import com.swanclouds.redfish.internal.BaseUpdateService;
import com.swanclouds.redfish.updates.domin.UpdateFirmwareModel;
import com.swanclouds.redfish.updates.domin.UpdateModel;

import java.util.Map;

/**
 * Author: HuangFuYuHui
 * Title: UpdateServiceImpl
 * Description: 服务器当前升级服务。
 * Date: 2022/7/27 10:36
 */
public class UpdateServiceImpl extends BaseUpdateService implements UpdateService {

    /**
     * 查询服务器当前升级服务资源的信息。
     * @return Update
     **/
    @Override
    public Update get() {
        return get(UpdateModel.class, uri(ClientConstants.PATH_UPDATESERVICE)).execute();
    }

    /**
     * 升级服务器固件。
     * @param  simpleUpdate 升级服务器固件请求参数
     * @return  com.swanclouds.model.common.ActionResponse
     **/
    @Override
    public ActionResponse updateServiceSimpleUpdate(SimpleUpdate simpleUpdate) {
        Preconditions.checkNotNull(simpleUpdate, "simpleUpdate is null");
        Update update = get();
        Map<String, Object> action = update.getAction();
        if (action.containsKey("#UpdateService.SimpleUpdate") && action.get("#UpdateService.SimpleUpdate") != null) {
            Map<String,Object> UpdateServiceSimpleUpdate = (Map<String, Object>)action.get("#UpdateService.SimpleUpdate");
            if (UpdateServiceSimpleUpdate.containsKey("target") && UpdateServiceSimpleUpdate.get("target") != null) {
                return post(ActionResponse.class,uri(UpdateServiceSimpleUpdate.get("target").toString()))
                        .header(ClientConstants.HEADER_CONTENT_TYPE,ClientConstants.CONTENT_TYPE_JSON)
                        .entity(simpleUpdate)
                        .execute();
            }
        }
        throw new ResourceNotFoundException("UpdateService.SimpleUpdate");
    }

    /**
     *  查询服务器当前升级固件任务的状态信息 华为不可用 宁畅可用
     * @return  com.swanclouds.model.updates.UpdateFirmware
     **/
    @Override
    public UpdateFirmware getUpdateFirmware() {
        return get(UpdateFirmwareModel.class,uri(ClientConstants.PATH_TASKSERVICE_TASKS_UPDATEFIRMWARE)).execute();
    }

    /**
     * 查询可升级固件集合资源信息服务
     * @return FirmwareInventoryService
     **/
    @Override
    public FirmwareInventoryService firmwareInventory() {
        return Apis.get(FirmwareInventoryService.class);
    }
}
